package org.example.xf;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.helper.StringUtil;

/**
 * @Description: TODO
 * @Author wyatt
 * @Data 2024/07/11 19:53
 */
@Slf4j
public class WmChatUtil {

    public static final String URL = "https://us-weimobopenai-online08.openai.azure.com/openai/deployments/gpt-4o-mini/chat/completions?api-version=2024-02-01&api-key=77cc1e84afe64095841a6b593f9071bb";

    private static final String BODY = "{\"stream\":false,\"temperature\":0.1,\"top_p\":1,\"frequency_penalty\":0,\"presence_penalty\":0,\"n\":1,\"messages\":[{\"role\":\"user\",\"content\":\"CONTENTKEY\"}]}";

    private static final String NEW_BODY = "{\"stream\":false,\"temperature\":0.1,\"top_p\":1,\"frequency_penalty\":0,\"presence_penalty\":0,\"n\":1,\"messages\":[{\"role\":\"user\",\"content\":\"CONTENTKEY\"},{\"role\":\"user\",\"content\":\"参考一下分类：客服响应慢/欺诈与不诚信/产品未发货/账户锁定问题/退款处理困难/域名丢失与管理/软件操作不便/付款与收费问题/销售与客户流失/技术支持缺乏/退货流程复杂/错误的促销信息/服务质量下降/网站运行不稳定/提供虚假信息/客户体验糟糕/账户被误收费/多次联系无回应/社交媒体销售问题/网站建设复杂/不公正资金扣留/店铺关闭无解释/退款问题频发/欺诈交易警告/订单未送达/高额隐性费用/账户被锁定/货物与广告不符/难以取消订阅/投诉无回应/法律行动威胁/高风险交易警告/账户管理混乱/支付问题频繁/体验分享警告/不满意的商家支持/不透明的收费政策/账户禁用/支付延迟/隐藏费用/退款政策不公/界面复杂/使用体验差/售后服务缺失/人工客服缺乏/支持响应慢/商家信任危机/用户挫败感/整体满意度低/小企业不适用/系统复杂性/订单处理问题/社区支持不足/服务不一致/难以联系管理层/客户服务差/资金冻结/产品未送达/账户关闭/转账问题/平台不可靠/支付问题/不合规行为/技术支持不足/退款难/订单延迟/供应商问题/负面影响品牌/赔偿争议/无法联系/投诉处理慢\"}]}";
    private static final String NEW_BODY_1 = "{\"stream\":false,\"temperature\":0.1,\"top_p\":1,\"frequency_penalty\":0,\"presence_penalty\":0,\"n\":1,\"messages\":[{\"role\":\"user\",\"content\":\"CONTENTKEY\"},{\"role\":\"user\",\"content\":\"参考一下分类：客服体验极差/无法控制诈骗行为/收费太高，性价比低/商店无故被封/平台缺乏安全性/SEO优化困难/使用体验不佳，不推荐给新手/附加费用繁多/定制化选择有限/界面老旧，使用不便/功能需插件，收费繁琐/模板选择少，缺乏灵活性/客服差，支持不够/学习曲线陡峭，设置复杂/适合简单电商，功能基础/易用性一般，非最佳选择/分析功能有限，数据不准确/缺乏定制，模板不够灵活/需要额外付费获取功能/购物体验不佳，界面不直观/依赖第三方应用，更新滞后/价格对小企业高/移动端体验需改善/自定义程度高，建店便捷/界面友好，操作简单，用户体验好/免费试用，社区支持强/生态插件丰富/简单易用，适合新手/主题模版丰富/客户支持好/设置简单，界面直观/功能丰富，适合电商/多平台整合/销售产品方便快捷/店铺设置简化，轻松上线产品并进行销售/多渠道销售集成，包括SEO、Google购物、邮件营销等/通过应用整合其他程序，灵活性高/国际支付处理整合便捷/监控销售和数据分析方便/全球化支持/移动端账户访问体验好\"}]}";

    private static final String NEW_BODY_2 = "{\"stream\":false,\"temperature\":0.1,\"top_p\":1,\"frequency_penalty\":0,\"presence_penalty\":0,\"n\":1,\"messages\":[{\"role\":\"user\",\"content\":\"CONTENTKEY\"},{\"role\":\"user\",\"content\":\"参考一下分类：平台收费高，性价比低/缺乏个性化选项/退款困难/网站性能差/免费版限制多/成本低，适合预算有限者/易于使用，适合初学者/模板数量多且美观/设置网站快速简便/提供必要的基本工具/修改设计非常方便/网站编辑器友好，功能多样/提供良好的支持和服务/易于集成其他功能和应用/集成能力有限/界面丑陋/使用困难/选择不多/SEO功能弱/客服难以联系/功能不稳定/缺乏分析功能/隐形费用多/自定义限制多/移动端体验不佳\"}]}";

    private static final String NEW_BODY_3 = "{\"stream\":false,\"temperature\":0.1,\"top_p\":1,\"frequency_penalty\":0,\"presence_penalty\":0,\"n\":1,\"messages\":[{\"role\":\"user\",\"content\":\"CONTENTKEY\"},{\"role\":\"user\",\"content\":\"参考一下分类：插件种类丰富，易于扩展/与WordPress完美兼容/免费使用，设置简单/易于管理，功能强大/支持多种支付方式/社区支持活跃，资源丰富/适合不同规模的商家/SEO优化，提升可见性/可自定义，灵活性高/用户友好，适合初学者/强大的社区支持/设计灵活，响应快速/安全性高，稳定性好/开源平台，自由度高/插件扩展费用高/性能较慢/更新频繁，插件不兼容/缺乏用户支持，客服响应慢/定制化有限，需额外付费/安全性需改进/学习曲线较陡/移动端追踪功能待优化/对新手略显复杂/更新频率过高/物流选项较弱/多个插件影响性能\"}]}";

    public static String chatTranslate(String content){
        if(StringUtil.isBlank(content)){
            return "";
        }
        return retryChat("翻译成中文: ".concat(content));
    }

    public static String chatTranslateSimple(String content){
        if(StringUtil.isBlank(content)){
            return "";
        }
        String res = retryChat("用中文总结下面这段评论（5个字）: ".concat(content));
        return res.substring(0, Math.min(res.length(), 5));
    }

    public static String chatClassify(String content, int index){
        if(StringUtil.isBlank(content)){
            return "";
        }
        String body = "";
        if(index == 1){
            body = NEW_BODY_1;
        } else if (index == 2) {
            body = NEW_BODY_2;
        }else {
            body = NEW_BODY_3;
        }

        String res = retryChat("分析给出分类，最多返回10个字， 不返回标点符号:  ".concat(content), body);
        return res.substring(0, Math.min(res.length(), 100));
    }

    public static String chatEvaluate(String content){
        if(StringUtil.isBlank(content)){
            return "";
        }
        String result =  retryChat("分析，返回好评/中评/差评/非评论:  ".concat(content));

        if (result.equals("好评") || result.equals("中评") || result.equals("差评")) {
            return result;
        }

        return "无法评价";
    }

    public static String retryChat(String content){
        int maxRetries = 3; // 设置最大重试次数
        for (int i = 0; i < maxRetries; i++) {
            try {
                // 尝试执行可能会失败的操作
                String result = chat(content);
                if("xf chat error".equals(result)){
                    continue;
                }
                // 如果操作成功，跳出循环
                return result;
            } catch (Exception e) {
                // 如果操作失败，打印错误信息并继续下一次循环尝试
                log.info("操作失败，正在重试...");
            }
        }
        return "xf chat error";
    }

    public static String retryChat(String content, String newBody){
        int maxRetries = 3; // 设置最大重试次数
        for (int i = 0; i < maxRetries; i++) {
            try {
                // 尝试执行可能会失败的操作
                String result = chat(content, newBody);
                if("xf chat error".equals(result)){
                    continue;
                }
                // 如果操作成功，跳出循环
                return result;
            } catch (Exception e) {
                // 如果操作失败，打印错误信息并继续下一次循环尝试
                log.info("操作失败，正在重试...");
            }
        }
        return "xf chat error";
    }

    private static String chat(String content){
        if(StringUtil.isBlank(content)){
            return "";
        }
        long startTime = System.currentTimeMillis();
        try {
           content = content.replaceAll("\"", "").replaceAll("\t", "")
                   .replaceAll("https://", "").replaceAll("http://", "")
                   .replaceAll("Show More", "");
           String bodyNew = BODY.replace("CONTENTKEY", content);
           String result = HttpRequest.post(URL)
                   .body(bodyNew)
                   .header("Content-Type", "application/json")
                   .timeout(10000)
                   .execute().body();

           log.info("chat result : {}", result);
           ChatRep chatRep = JSON.parseObject(result, ChatRep.class );

           long endTime = System.currentTimeMillis();
           long elapsedTime = endTime - startTime;
           String out = chatRep.getChoices().get(0).getMessage().getContent();
           log.info("chat elapsed :{} , in : {}, out : {}", elapsedTime, content, out);
           return out;
       }catch (Exception e) {
           return "xf chat error";
       }
    }

    private static String chat(String content, String newBody){
        if(StringUtil.isBlank(content)){
            return "";
        }
        long startTime = System.currentTimeMillis();
        try {
            content = content.replaceAll("\"", "").replaceAll("\t", "")
                    .replaceAll("https://", "").replaceAll("http://", "")
                    .replaceAll("Show More", "");
            String bodyNew = newBody.replace("CONTENTKEY", content);
            String result = HttpRequest.post(URL)
                    .body(bodyNew)
                    .header("Content-Type", "application/json")
                    .timeout(10000)
                    .execute().body();

            log.info("chat result : {}", result);
            ChatRep chatRep = JSON.parseObject(result, ChatRep.class );

            long endTime = System.currentTimeMillis();
            long elapsedTime = endTime - startTime;
            String out = chatRep.getChoices().get(0).getMessage().getContent();
            log.info("chat elapsed :{} , in : {}, out : {}", elapsedTime, content, out);
            return out;
        }catch (Exception e) {
            return "xf chat error";
        }
    }

    public static void main(String[] args) {
        System.out.println(chat("分析给出分类，最多返回10个字， 不返回标点符号:  Shopify%20USED%20to%20be%20good%2C%20now%20horrible%09I'm%20going%20through%20a%20very%20similar%20and%20INCREDIBLY%20frustrating%20situation.%20I%20received%20an%20email%20almost%202%20weeks%20ago%20saying%20they%20'couldn't%20verify%20my%20Shopify%20payments%20information.%20Contact%20support%2C%20but%20I%20had%20NOT%20done%20or%20changed%20anything%20to%20my%20account.%20I%20tried%20to%20login%20to%20see%20if%20everything%20was%20in%20order%2C%20but%20I%20was%20locked%20out!%20And%20then%20I%20realized%20my%20store%20was%20offline%2C%20even%20though%20I%20have%20PAID%20FOR%20AN%20ENTIRE%20YEAR%20of%20monthly%20operating%20fees%20(and%20have%205%20months%20left)!!!!%20I've%20contacted%20them%20several%20times%2C%20(online)%20chatted%20with%202%20different%20advisors%20(because%20they%20no%20longer%20offer%20phone%20support)%20who%20assured%20me%20it%20would%20be%20resolved%20right%20away...%20STILL%20NOTHING.%20Now%20I%20have%20(long%20term)%20customers%20reaching%20out%20to%20me%20on%20my%20private%20email%2C%20wondering%20why%20they%20can't%20access%20my%20store!!!%20This%20is%20absolutely%20ridiculous.%20They%20lock%20me%20out%20of%20my%20account%20that%20is%20paid%20in%20full%2C%20and%20take%20my%20store%20offline%3F%3F%3F%20I've%20been%20with%20them%20for%20MANY%20years%20and%20used%20to%20love%20them%2C%20but%20I%20experienced%20a%20similar%20thing%20last%20year%2C%20so%20I'm%20100%25%20done%20with%20them.%20Hope%20people%20read%20this%20forum%20before%20signing%20up%20with%20them"));
    }


}
